﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.Framework.Configurations.Core
{
    class HtmlRow : IHtmlRow
    {
        string parentpath;

        int nestLevel = 0;

        int tableIndex = 0;

        int rowIndex = 0;

        IHtmlNode node;

        public HtmlRow(IHtmlNode node, string parentpath, int nestLevel, int tableIndex, int rowIndex)
        {
            this.parentpath = parentpath;
            this.tableIndex = tableIndex;
            this.nestLevel = nestLevel;
            this.rowIndex = rowIndex;
            this.node = node;
        }

        public string ParentPath
        {
            get { return parentpath; }
            set { parentpath = value; }
        }

        public int NestLevel
        {
            get { return nestLevel; }
            set { nestLevel = value; }
        }

        public int TableIndex
        {
            get { return tableIndex; }
            set { tableIndex = value; }
        }

        public int RowIndex
        {
            get { return rowIndex; }
            set { rowIndex = value; }
        }

        public string Content
        {
            get { return node.Serialize(); }
        }

        public IHtmlNode HtmlNode
        {
            get { return node; }
        }

        public IHtmlCell[] Cells
        {
            get
            {
                List<IHtmlCell> cells = new List<IHtmlCell>();

                int nodeindex = 0;

                foreach (IHtmlNode subnode in node.Nodes)
                {
                    if (!string.Equals(subnode.ElementName, "td", StringComparison.OrdinalIgnoreCase))
                        continue;

                    cells.Add(new HtmlCell(subnode, parentpath, nestLevel, TableIndex, rowIndex, nodeindex++));
                }

                return cells.ToArray();
            }
        }

        public string Serialize()
        {
            FormatStringBuilder builder = new FormatStringBuilder();
            for (int i = 0; i < nestLevel * 3; i++)
                builder.Indent();

            builder.Indent();
            builder.AppendLine(string.Format("<row path='{0}{1}.{2}' nest='{3}'>", parentpath, tableIndex, rowIndex, nestLevel));
            foreach (IHtmlCell cell in Cells)
            {
                builder.Append(cell.Serialize());
            }
            builder.AppendLine("</row>");
            builder.Outdent();

            for (int i = 0; i < nestLevel * 3; i++)
                builder.Outdent();

            return builder.ToString();
        }


    }
}
